// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        books: [],
        searchQuery: ''
    },
    mutations: {
        SET_BOOKS(state, books) {
            state.books = books;
        },
        SET_SEARCH_QUERY(state, query) {
            state.searchQuery = query;
        }
    },
    actions: {
        async searchBooks({ commit }, query) {
            try {
                const response = await axios.get('/api/books/search', { params: { query } });
                commit('SET_BOOKS', response.data);
            } catch (error) {
                console.error('Error fetching books:', error);
            }
        },
        async borrowBook({ dispatch }, bookId) {
            try {
                await axios.post(`/api/books/borrow/${bookId}`);
                alert('借书成功');
                dispatch('searchBooks', this.state.searchQuery);
            } catch (error) {
                console.error('Error borrowing book:', error);
            }
        },
        async returnBook({ dispatch }, bookId) {
            try {
                await axios.post(`/api/books/return/${bookId}`);
                alert('还书成功');
                dispatch('searchBooks', this.state.searchQuery);
            } catch (error) {
                console.error('Error returning book:', error);
            }
        }
    },
    getters: {
        books: state => state.books,
        searchQuery: state => state.searchQuery
    }
});